/**
 * 数组元素添加name字段
 * @param data
 * @param nameKey
 * @return {Array}
 */
export function formatterListName(data = [], nameKey = 'nameKey') {
  if (data && nameKey) {
    data.forEach(item => {
      item.name = item[nameKey] || '';
    });
  }
  return data;
}

/**
 * 将数据转成AtIndexes需要的数据
 * @param data [{cityName:"测试城市",initial:"0",cityCode:"0001-testsf1-0101",grade:10,cityId:30000054}]
 * @param fieldKey
 * @return {Array} [{title: 'A', key: 'A', items: [name: '列表项内容']}]
 */
export let formatterDataToIndexList = (data = [], fieldKey = 'initial') => {
  let list = [];

  if (data && data.length > 0) {
    let sortData = dataLetterSort(data, fieldKey);
    for (let key in sortData) {
      list.push({
        title: key,
        key: key,
        items: sortData[key]
      });
    }
  }

  return list;
};

/**
 * 数据按照拼音首字母排序并分组
 * @param data 需要排序的数据 [{cityName:"测试城市",initial:"0",cityCode:"0001-testsf1-0101",grade:10,cityId:30000054}]
 * @param {String} field 必须, 排序所依据的字段名
 * @return {*} 例如：{A:[{}, {}], B:[{}, {}], C:[{}], #:[]}
 */
function dataLetterSort(data = [], field = 'key') {
  let letterReg = /^[A-Z]$/;
  let list = [];

  let hasNotCase = false
  for (let item of data) {
    // 首字母转大写英文
    let letter = (item[field]).substr(0, 1).toUpperCase();

    // 是否大写英文字母, 非字母添加#分组，用来存放首字母不能转为大写英文的数据
    if (!letterReg.test(letter)) {
      letter = '#'
      hasNotCase = true
    }

    // 创建字母分组
    if (!(letter in list)) {
      list[letter] = [];
    }

    // 字母分组添加数据
    list[letter].push(item);
  }

  // 转换格式进行排序；

  let result = [];
  for (let key in list) {
    result.push({
      letter: key,
      list: list[key]
    });
  }
  result.sort(function (x, y) {
    return x.letter.charCodeAt(0) - y.letter.charCodeAt(0);
  });
  // #号分组放最后
  if (hasNotCase) {
    let lastArr = result[0];
    result.splice(0, 1);
    result.push(lastArr);
  }

  // 转换数据格式
  let jsonSort = {};
  for (let i = 0, len = result.length; i < len; i++) {
    jsonSort[result[i].letter] = result[i].list;
  }

  return jsonSort;
}

/**
 * js过滤数组
 * @param data
 * @param nameKey
 * @param regStr
 * @return {Array}
 */
export function findDataByKeyInList(data = [], nameKey = '', regStr = '') {
  let result = [];

  if (data && nameKey && regStr) {
    data.forEach(item => {
      if (item[nameKey].indexOf(regStr) > -1) {
        result.push(item);
      }
    });
  }

  return result;
}

/**
 * 时间格式化
 * @param date
 * @returns {string}
 */
export function renderTime(nameKey = '') {
  var da = new Date(parseInt(nameKey.replace("/Date(", "").replace(")/", "").split("+")[0]));
  var Month = da.getMonth() + 1;
  var Day = da.getDate();
  var CurrentDate = "";
  if (Month >= 10) {
    CurrentDate += Month + "-";
  } else {
    CurrentDate += "0" + Month + "-";
  }
  if (Day >= 10) {
    CurrentDate += Day;
  } else {
    CurrentDate += "0" + Day;
  }
  return CurrentDate;
}

/**
 * 时间相减函数
 * @param date
 * @returns {string}
 */
export function renderTimeMus(nameKey) {
  var end_date = new Date(nameKey);
  var start_date = new Date();
  var days = end_date.getTime() - start_date.getTime();
  var day = parseInt(days / (1000 * 60 * 60 * 24));
  return day;
}

/**
 * 日期补0
 * @param date number类型
 * @returns {any} string类型
 */
export function formatterDateZero(dates) {
  var dateStr = dates.toString();
  if (dates < 10) {
    dateStr = '0' + dates;
  }
  return dateStr;
}


/**
 * 时间戳格式化函数
 * @param  {string} format    格式
 * @param  {int}    timestamp 要格式化的时间 默认为当前时间
 * @return {string}           格式化的时间字符串
 */
export function date(format, timestamp) {
  var ret, jsdate = ((timestamp) ? new Date(timestamp) : new Date());
  var pad = function (n, c) {
    if ((n = n + "").length < c) {
      return new Array(++c - n.length).join("0") + n;
    } else {
      return n;
    }
  };
  var txt_weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  var txt_ordin = {1: "st", 2: "nd", 3: "rd", 21: "st", 22: "nd", 23: "rd", 31: "st"};
  var txt_months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  var f = {
    // Day
    d: function () {
      return pad(f.j(), 2)
    },
    D: function () {
      return f.l().substr(0, 3)
    },
    j: function () {
      return jsdate.getDate()
    },
    l: function () {
      return txt_weekdays[f.w()]
    },
    N: function () {
      return f.w() + 1
    },
    S: function () {
      return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th'
    },
    w: function () {
      return jsdate.getDay()
    },
    z: function () {
      return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0
    },

    // Week
    W: function () {
      var a = f.z(), b = 364 + f.L() - a;
      var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
      if (b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b) {
        return 1;
      } else {
        if (a <= 2 && nd >= 4 && a >= (6 - nd)) {
          nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
          return date("W", Math.round(nd2.getTime() / 1000));
        } else {
          return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
        }
      }
    },

    // Month
    F: function () {
      return txt_months[f.n()]
    },
    m: function () {
      return pad(f.n(), 2)
    },
    M: function () {
      return f.F().substr(0, 3)
    },
    n: function () {
      return jsdate.getMonth() + 1
    },
    t: function () {
      var n;
      if ((n = jsdate.getMonth() + 1) == 2) {
        return 28 + f.L();
      } else {
        if (n & 1 && n < 8 || !(n & 1) && n > 7) {
          return 31;
        } else {
          return 30;
        }
      }
    },

    // Year
    L: function () {
      var y = f.Y();
      return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0
    },
    //o not supported yet
    Y: function () {
      return jsdate.getFullYear()
    },
    y: function () {
      return (jsdate.getFullYear() + "").slice(2)
    },

    // Time
    a: function () {
      return jsdate.getHours() > 11 ? "pm" : "am"
    },
    A: function () {
      return f.a().toUpperCase()
    },
    B: function () {
      // peter paul koch:
      var off = (jsdate.getTimezoneOffset() + 60) * 60;
      var theSeconds = (jsdate.getHours() * 3600) + (jsdate.getMinutes() * 60) + jsdate.getSeconds() + off;
      var beat = Math.floor(theSeconds / 86.4);
      if (beat > 1000) beat -= 1000;
      if (beat < 0) beat += 1000;
      if ((String(beat)).length == 1) beat = "00" + beat;
      if ((String(beat)).length == 2) beat = "0" + beat;
      return beat;
    },
    g: function () {
      return jsdate.getHours() % 12 || 12
    },
    G: function () {
      return jsdate.getHours()
    },
    h: function () {
      return pad(f.g(), 2)
    },
    H: function () {
      return pad(jsdate.getHours(), 2)
    },
    i: function () {
      return pad(jsdate.getMinutes(), 2)
    },
    s: function () {
      return pad(jsdate.getSeconds(), 2)
    },

    O: function () {
      var t = pad(Math.abs(jsdate.getTimezoneOffset() / 60 * 100), 4);
      if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
      return t;
    },
    P: function () {
      var O = f.O();
      return (O.substr(0, 3) + ":" + O.substr(3, 2))
    },


    // Full Date/Time
    c: function () {
      return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P()
    },
    //r not supported yet
    U: function () {
      return Math.round(jsdate.getTime() / 1000)
    }
  };

  return format.replace(/[\\]?([a-zA-Z])/g, function (t, s) {
    if (t != s) {
      // escaped
      ret = s;
    } else if (f[s]) {
      // a date function exists
      ret = f[s]();
    } else {
      // nothing special
      ret = s;
    }

    return ret;
  });
}


export function formatDecorationDate(date) {
  if (!date) {
    return
  }
  var date = new Date(date);
  var YY = date.getFullYear() + '年';
  var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
  var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + '日';
  var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
  var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
  return YY + MM + DD + hh + mm + ss;
}

export function date_to_timemillies(date) {

}

export function formatDate(date) {
  var date = new Date(date);
  var YY = date.getFullYear() + '-';
  var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
  var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
  var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
  var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
  return MM + DD + " " + hh + mm;
}

/**
 * 时间戳格式化函数
 * @param  {string} format    格式
 * @param  {int}    timestamp 要格式化的时间 默认为当前时间
 * @return {string}           格式化的时间字符串
 */

export function FormatTime(format, timestamp) {
  var start = timestamp;
  var end = new Date();
  if (start != "" || end != "") {
    if (start != "" && end != "" && start <= end) {
      var sjc = end.getTime() - start;    //时间差的毫秒数
      var days = Math.floor(sjc / (24 * 3600 * 1000));  //计算出相差天数
      var leave1 = sjc % (24 * 3600 * 1000);             //计算天数后剩余的毫秒数
      var hours = Math.floor(leave1 / (3600 * 1000));  //计算出小时数

      var leave2 = leave1 % (3600 * 1000);             //计算小时数后剩余的毫秒数
      var minutes = Math.floor(leave2 / (60 * 1000));  //计算相差分钟数
      var leave3 = leave2 % (60 * 1000);               //计算分钟数后剩余的毫秒数
      var seconds = Math.round(leave3 / 1000);       //计算相差秒数
      if (days == 0 && hours == 0 && minutes == 0) {
        return seconds + "秒前发布"
      } else if (days == 0 && hours == 0) {
        return minutes + "分钟前发布"
      } else if (days == 0) {
        return hours + "小时前发布"
      } else if (days > 0 && days < 3) {
        return days + "天前发布"
      } else {
        return date(format, timestamp) + "发布"
      }
    }
  }
}


export function FormatBbsTime(format, timestamp) {
  var start = timestamp;
  var end = new Date();
  if (start != "" || end != "") {
    if (start != "" && end != "" && start <= end) {
      var sjc = end.getTime() - start;    //时间差的毫秒数
      var days = Math.floor(sjc / (24 * 3600 * 1000));  //计算出相差天数
      var leave1 = sjc % (24 * 3600 * 1000);             //计算天数后剩余的毫秒数
      var hours = Math.floor(leave1 / (3600 * 1000));  //计算出小时数

      var leave2 = leave1 % (3600 * 1000);             //计算小时数后剩余的毫秒数
      var minutes = Math.floor(leave2 / (60 * 1000));  //计算相差分钟数
      var leave3 = leave2 % (60 * 1000);               //计算分钟数后剩余的毫秒数
      var seconds = Math.round(leave3 / 1000);       //计算相差秒数
      if (days == 0 && hours == 0 && minutes == 0) {
        return seconds + "秒前"
      } else if (days == 0 && hours == 0) {
        return minutes + "分钟前"
      } else if (days == 0) {
        return hours + "小时前"
      } else if (days > 0 && days < 3) {
        return days + "天前"
      } else {
        return date(format, timestamp)
      }
    }
  }
}

export function FormatDate(timestamp) {
  var start = timestamp;
  if (start != "") {
    var sjc = start;
    var days = Math.floor(sjc / (24 * 3600 * 1000));  //计算出相差天数
    var leave1 = sjc % (24 * 3600 * 1000);             //计算天数后剩余的毫秒数
    var hours = Math.floor(leave1 / (3600 * 1000));  //计算出小时数
    var leave2 = leave1 % (3600 * 1000);             //计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60 * 1000));  //计算相差分钟数
    var leave3 = leave2 % (60 * 1000);               //计算分钟数后剩余的毫秒数
    var seconds = Math.round(leave3 / 1000);       //计算相差秒数

    if (days == 0 && hours == 0 && minutes == 0) {
      return '00:00:' + formatterDateZero(seconds)
    } else if (days == 0 && hours == 0) {
      return '00:' + formatterDateZero(minutes) + ':' + formatterDateZero(seconds)
    } else if (days == 0) {
      return formatterDateZero(hours) + ':' + formatterDateZero(minutes) + ':' + formatterDateZero(seconds)
    }
  }
}


export function FormatPassDate(timestamp) {
  var start = timestamp;
  if (start != "") {
    var d, h, m, s, ms;
    d = Math.floor(start / 1000 / 60 / 60 / 24);
    h = Math.floor(start / 1000 / 60 / 60 % 24);
    m = Math.floor(start / 1000 / 60 % 60);
    s = Math.floor(start / 1000);
    ms = Math.floor(start % 1000);
    ms = ms < 100 ? "0" + ms : ms;
    s = s < 10 ? "00" + s : (s < 100 ? "0" + s : s);
    m = m < 10 ? "0" + m : m;
    h = h < 10 ? "0" + h : h;
    return (s >= 300 ? 300 : s) + ':' + (s >= 300 ? "000" : ms)
    // if (days == 0 && hours == 0 && minutes == 0) {
    //   return '00:00:' + formatterDateZero(seconds)
    // } else if (days == 0 && hours == 0) {
    //   return '00:' + formatterDateZero(minutes) + ':' + formatterDateZero(seconds)
    // } else if (days == 0) {
    //   return formatterDateZero(hours) + ':' + formatterDateZero(minutes) + ':' + formatterDateZero(seconds)
    // }
  }
}


export function calTime(timestamp) {
  var start = timestamp;
  var end = new Date();
  if (start != "" || end != "") {
    if (start != "" && end != "" && start <= end) {
      var sjc = end.getTime() - start;    //时间差的毫秒数
      var days = Math.floor(sjc / (24 * 3600 * 1000));  //计算出相差天数
      if (days > 1) {
        return true
      } else {
        return false
      }
    }
  }
}


/**
 * 0---即将到期   1-----有效期
 * @param format
 * @param timestamp
 * @returns {number}
 * @constructor
 */
export function FormatTimes(format, timestamp) {
  var start = new Date();
  var end = timestamp;
  if (start != "" || end != "") {
    if (start != "" && end != "" && start <= end) {
      var sjc = end - start.getTime();    //时间差的毫秒数
      var days = Math.floor(sjc / (24 * 3600 * 1000));  //计算出相差天数
      var leave1 = sjc % (24 * 3600 * 1000);             //计算天数后剩余的毫秒数
      var hours = Math.floor(leave1 / (3600 * 1000));  //计算出小时数

      var leave2 = leave1 % (3600 * 1000);             //计算小时数后剩余的毫秒数
      var minutes = Math.floor(leave2 / (60 * 1000));  //计算相差分钟数
      var leave3 = leave2 % (60 * 1000);               //计算分钟数后剩余的毫秒数
      var seconds = Math.round(leave3 / 1000);       //计算相差秒数

      if (days > 0 && days < 3) {
        return 0
      } else {
        return 1
      }
    } else {
      return 1
    }
  }
}


export function FormatFlowerTime(format, timestamp) {
  var start = timestamp;
  var end = new Date();
  if (start != "" || end != "") {
    if (start != "" && end != "" && start <= end) {
      var sjc = end.getTime() - start;    //时间差的毫秒数
      var days = Math.floor(sjc / (24 * 3600 * 1000));  //计算出相差天数
      var leave1 = sjc % (24 * 3600 * 1000);             //计算天数后剩余的毫秒数
      var hours = Math.floor(leave1 / (3600 * 1000));  //计算出小时数

      var leave2 = leave1 % (3600 * 1000);             //计算小时数后剩余的毫秒数
      var minutes = Math.floor(leave2 / (60 * 1000));  //计算相差分钟数

      var leave3 = leave2 % (60 * 1000);               //计算分钟数后剩余的毫秒数
      var seconds = Math.round(leave3 / 1000);       //计算相差秒数

      if (days == 0 && hours == 0 && minutes == 0) {
        return seconds + "秒前发布"
      } else if (days == 0 && hours == 0) {
        return minutes + "分钟前"
      } else if (days == 0) {
        return hours + "小时前"
      } else if (days > 0 && days < 3) {
        return days + "天前"
      } else {
        return date(format, timestamp)
      }
    }
  }
}

export function FormatSeckillTime(timestamp) {
  var start = new Date();
  var end = timestamp;

  if (start != "" || end != "") {
    if (start != "" && end != "" && start <= end) {
      var sjc = end - start.getTime();    //时间差的毫秒数
      var days = Math.floor(sjc / (24 * 3600 * 1000));  //计算出相差天数
      var leave1 = sjc % (24 * 3600 * 1000);             //计算天数后剩余的毫秒数
      var hours = Math.floor(leave1 / (3600 * 1000));  //计算出小时数

      var leave2 = leave1 % (3600 * 1000);             //计算小时数后剩余的毫秒数
      var minutes = Math.floor(leave2 / (60 * 1000));  //计算相差分钟数
      var leave3 = leave2 % (60 * 1000);               //计算分钟数后剩余的毫秒数
      var seconds = Math.round(leave3 / 1000);       //计算相差秒数
      if (days == 0 && hours == 0 && minutes == 0) {
        return 0
      } else if (days == 0 && hours == 0) {
        return minutes + "分钟"
      } else if (days == 0) {
        return hours + "小时" + minutes + "分钟"
      } else if (days > 0) {
        return days + "天" + hours + "小时" + minutes + "分钟"
      } else {
        return 0
      }
    }
  } else {
    return 0
  }
}

export function getQueryStringArgs(url) {
  if (url.lastIndexOf("?") > -1) {
    var args = {}
    var qs = url.substring(url.lastIndexOf("?") + 1);
    var items = qs.length > 0 ? qs.split('&') : []
    var item = null
    var name = null
    var value = null
    for (var i = 0; i < items.length; i++) {
      item = items[i].split("=")
      //用decodeURIComponent()分别解码name 和value（因为查询字符串应该是被编码过的）。
      name = decodeURIComponent(item[0])
      value = decodeURIComponent(item[1])
      if (name.length) {
        args[name] = value
      }
    }
    return args;
  }
  return null;
}

// 获取 url '？'前部分
export function getQueryStringUrl(url) {
  if (url.indexOf("?") != -1) {
    url = url.split("?")[0];
    return url
  }
}


//步数格式化
export function formatNum(num) {
  let value = num;
  if ((num + '').length >= 9) {
    value = (num / 100000000).toFixed(2) + '亿'
  }
  return value
}


//健康步数数字格式化
export function formatBbsNum(num) {
  let value = num;
  if ((num + '').length >= 9) {
    value = parseFloat((num / 100000000) + '').toFixed(1) + '亿'
  } else if ((num + '').length >= 5) {
    value = parseFloat((num / 10000) + '').toFixed(1) + '万'
  }
  return value
}


//闲置
export function formatUnusedNum(num) {
  let value = num;
  if (!(value + '').split('.')[0]) {
    value = parseFloat(('0.' + (value + '').split('.')[1])).toFixed(2)
  } else if ((value + '').split('.')[0] && !(value + '').split('.')[1] && (value + '').split('.')[0].length < 5) {
    value = num
  } else if ((value + '').split('.')[0] && (value + '').split('.')[0].length < 5) {
    value = parseFloat(num + '').toFixed(2)
  } else if ((value + '').split('.')[0].length >= 9) {
    value = parseFloat((num / 100000000) + '').toFixed(2) + '亿'
  } else if ((value + '').split('.')[0].length >= 5) {
    value = parseFloat((num / 10000) + '').toFixed(2) + '万'
  }
  return value
}


//碳排量格式化
export function formatCarbon(num) {
  let value = num + 'g';
  if ((num + '').length >= 7) {
    value = (num / 1000000).toFixed(2) + 't'
  } else if ((num + '').length > 5) {
    value = (num / 1000).toFixed(2) + 'kg'
  }
  return value
}

//种树格式化
export function formatTree(num) {
  let value = num;
  if ((num + '').length > 3) {
    value = (num / 100) + '百'
  }
  return value
}


//健康步数数字格式化
export function formatStepNum(num) {
  let value = num;
  if ((value + '').split('.')[0].length >= 5) {
    value = parseFloat((num / 10000) + '').toFixed(1) + 'w'
  }
  return value
}

//健康步数数字格式化
export function formatTagNum(num) {
  let value = num;
  if ((value + '').split('.')[0].length >= 4) {
    value = parseFloat((num / 1000) + '').toFixed(1) + 'k'
  } else if ((value + '').split('.')[0].length >= 5) {
    value = parseFloat((num / 10000) + '').toFixed(1) + 'w'
  }
  return value
}


/**
 * 不四舍五入 保留2位
 * @param num
 * @param decimal
 */
export const formatDecimal = (num, decimal) => {
  num = num.toString();
  var index = num.indexOf('.');
  if (index !== -1) {
    num = num.substring(0, decimal + index + 1)
  } else {
    num = num.substring(0)
  }
  return parseFloat(num).toFixed(decimal)
}


export function getDaysInMonth(year, month) {
  let days = new Date(year, month, 0).getDate()
  return days
}
